#include "udp.h"
#include "recv_video_thread.h"

#include <string>
#include <cstdio>
#include <vector>

#include <QImage>

MyRecvVideoThread::MyRecvVideoThread(uint16_t listen_port, uint16_t ch)
{
    port = listen_port;
    channel = ch;
    stop_flag = false;
}

void MyRecvVideoThread::run()
{
    qRegisterMetaType<QImage>("QImage");

    udp::UDPReceiver udp_receiver;
    udp_receiver.set_listen_port(port);

    int failure_cnt = 0;
    std::vector<uint8_t> buffer;
    udp::RecvInfo info;
    QImage image;

    if (!udp_receiver.init())
    {
        emit update_video_log("图传网络组件启动失败！");
    }

    emit update_video_log("图传网络组件启动成功。");

    while (!stop_flag)
    {
        buffer = udp_receiver.recv(info);

        if (info.flag == FLAG_SUCCESS)
        {
            if (failure_cnt > 50)
            {
                emit update_video_log("图传信号恢复。");
            }
            failure_cnt = 0;
            image.loadFromData(buffer.data(), buffer.size(), "JPEG");
            image = image.scaled(971, 421);
            emit update_video_frame(image);
        }
        else
        {
            if (failure_cnt == 50)
            {
                emit update_video_log("图传信号丢失！");
            }
            if (failure_cnt <= 50)
            {
                failure_cnt += 1;
            }
        }
    }
}

void MyRecvVideoThread::stop()
{
    stop_flag = true;
}
